package leetcode.primary;

import utils.linkedList.LinkedList;
import utils.linkedList.ListNode;

public class T82 {
    public ListNode deleteDuplicates(ListNode head) {

        if (head==null || head.next==null ){
            return head;
        }
        ListNode left = head;           //指向重复元素的头
        ListNode right = head.next;         //指向重复元素块的尾
        ListNode l_left = left;         //指向重复元素的头的前一个结点
        int i = 1;
        while (right!=null){
            System.out.println("i="+i+",l_left="+l_left.val+",left="+left.val+",right="+right.val);
            i++;

            if (right.val==left.val){
                if (right.next!=null){
                    //找到重复元素块
                    if (right.next.val==left.val){
                        right=right.next;
                        continue;
                    }
                }
                //重复元素在头部
                if (left==head){
                    head = right.next;
                    l_left = head;
                }else {
                    l_left.next = right.next;
                }
                left = l_left;
                //重复元素在尾部
                if (left!=null ){
                    right = left.next;
                }else {
                    right=null;
                }

            }else {
                l_left = left;
                left = left.next;
                right = right.next;
            }

        }
        return head;
    }

    public static void main(String[] args) {
        T82 test = new T82();
        LinkedList linkedList = new LinkedList();
        ListNode head = linkedList.initLinkedList(new int[]{1,1,2,2,4,3,3});
        ListNode node = test.deleteDuplicates(head);
        while (node!=null){
            System.out.print(node.val+" ");
            node = node.next;
        }
    }
}